import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select,
  message
} from 'antd'
import ReactQuill from 'react-quill'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useSearchParams, useNavigate } from 'react-router-dom'
import { useEffect, useRef, useState } from 'react'
import { useStore } from '@/store'
import { observer } from 'mobx-react-lite'
import request from '@/utils/request'
import 'react-quill/dist/quill.snow.css'
import './index.scss'
const { Option } = Select


const Publish = () => {
  const navigate = useNavigate()

  // 引入仓库
  const store = useStore()
  // 定义上传数组
  const [fileList, setFileList] = useState([])
  // 定义一个图片上传暂存仓库
  const fileListRef = useRef([])
  const from = useRef()
  // 上传图片成功触发的函数
  const onUploadChange = ({ fileList }) => {
    // antd这里设置的是每上传一点就触发一次这个函数
    // 只有最后一次执行这个函数的时候才是上传完成
    setFileList(fileList)
    // 把图片存入仓库一份
    fileListRef.current = fileList

  }
  // 记录当前的图片显示数量
  const [imgCount, setImgCount] = useState(1)
  const changeType = e => {
    const count = e.target.value
    // 这里的修改是异步的，不能用imgCount做判断条件
    setImgCount(count)
    if (count === 1) {
      // 单图
      setFileList(fileListRef.current[0] ? [fileListRef.current[0]] : [])

    } else if (count === 3) {
      // 三图，展示所有图片
      setFileList(fileListRef.current)
    }
  }
  // 上传文章按钮
  const onFinish = async values => {
    const { channel_id, content, title, type } = values

    // 准备接口参数
    const data = {
      channel_id,
      content,
      title,
      type,
      cover: {
        type,
        Images: fileList.map(item => item.response?.data.url || item.url)
      }
    }
    if (id) {
      await request({
        method: 'PUT',
        url: `/mp/articles/${id}?draft=false`,
        data
      })
    } else {
      await request({
        method: 'POST',
        url: '/mp/articles?draft=false',
        data
      })
    }

    message.success(id ? '编辑成功' : '上传成功')
    // 清空表单
    from.current.resetFields()
    // 清空图片数据
    fileListRef.current = []
    setFileList([])
    // 跳转
    navigate('/article')
  }
  // 适配编辑文案
  const [param] = useSearchParams()
  const id = param.get('id')
  // 编辑数据回显
  useEffect(() => {
    const getArticle = async () => {
      const { data } = await request({
        url: `/mp/articles/${id}`
      })
      // 数据回填
      from.current.setFieldsValue({ ...data, type: data.cover.type })
      setImgCount(data.cover.type)
      // 回显图片
      const imageList = data.cover.images.map(url => ({ url }))
      setFileList(imageList)

    }
    if (id) {
      getArticle()
    }
  }, [id, navigate])
  return (
    <div className="publish">
      <Card
        title={
          <Breadcrumb separator=">"
            items={[
              {
                title: <Link to="/">首页</Link>
              },
              {
                title: `${id ? '编辑' : '发布'}文章`
              }
            ]} />
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1 }}
          onFinish={onFinish}
          ref={from}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              {store.Channels.list.map(item => (
                <Option value={item.id} key={item.id}>{item.name}</Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={changeType}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {
              // 判断是否要显示图片
              imgCount > 0 ? (
                <Upload
                  name="image"
                  listType="picture-card"
                  className="avatar-uploader"
                  showUploadList
                  action="http://geek.itheima.net/v1_0/upload"
                  fileList={fileList}
                  onChange={onUploadChange}
                  multiple={imgCount > 1}
                  maxCount={imgCount}
                >
                  <div style={{ marginTop: 8 }}>
                    <PlusOutlined />
                  </div>
                </Upload>
              ) : null
            }

          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {id ? '更新' : '发布'}文章
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default observer(Publish)